package com.quickcode.example.collection;

import com.quickcode.annotation.UnSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.List;
import java.util.Vector;

/**
 * Created by 张波 on 2019/10/24.
 */
@Slf4j
@UnSafe
public class VectorExample2 {

    public static final int clientTotal = 5000;

    public static final int threadTotal = 200;


    public static void main(String[] args) {
        List<Integer> vector = new Vector<>();
        vector.add(1);
        vector.add(2);
        vector.add(3);

//        test1(vector);
//        test2(vector);
//        test4(vector);
        test3(vector);
        System.out.println(vector);
    }

    //异常：java.util.ConcurrentModificationException
    public static void test1(List<Integer> vector) {
        for(Integer value : vector) {
            if(value.equals(3)) {
                vector.remove(value);
            }
        }
    }

    //当移除的是最新一个元素时会报：java.util.ConcurrentModificationException
    public static void test2(List<Integer> vector) {
        Iterator<Integer> iterator = vector.iterator();
        while (iterator.hasNext()) {
            Integer value = iterator.next();
            if(value.equals(2)) {
                vector.remove(value);
            }
        }
    }


    //success
    public static void test3(List<Integer> vector) {
        for(int i = 0 ; i < vector.size() ; ++i) {
            if(vector.get(i).equals(3)) {
                vector.remove(vector.get(i));
            }
        }
    }

    // java.util.ConcurrentModificationException
    public static void test4(List<Integer> vector) {
        Iterator<Integer> iterator = vector.iterator();
        while (iterator.hasNext()) {
            Integer value = iterator.next();
            if(value.equals(3)) {
                vector.remove(value);
            }
        }
    }
}
